<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物品采购清单</title>
    <link rel="stylesheet" href="../css/all.min.css">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            line-height: 1.6;
            background-color: #f9f9f9;
            color: #333;
        }
        
        .container {
            width: 21cm;
            padding: 1.5cm;
            margin: 20px auto;
            box-sizing: border-box;
            background-color: #fff;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            border-radius: 8px;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid #667eea;
        }
        
        .report-title {
            font-size: 28px;
            font-weight: bold;
            color: #667eea;
            margin: 0;
            letter-spacing: 1px;
        }
        
        .purchase-info {
            font-size: 16px;
            margin-bottom: 25px;
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 15px;
        }
        
        .purchase-info span {
            padding: 8px 12px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
            background-color: #f5f9ff;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 30px;
            font-size: 14px;
        }
        
        th, td {
            padding: 12px 15px;
            text-align: center;
            border: 1px solid #e0e0e0;
        }
        
        th {
            background-color: #f0f7ff;
            font-weight: bold;
            color: #2c3e50;
        }
        
        .editable {
            min-height: 20px;
            outline: none;
            display: block;
            padding: 5px;
            transition: all 0.2s ease;
        }
        
        .editable:focus {
            background-color: #f5f9ff;
            border-radius: 3px;
        }
        
        .summary {
            text-align: right;
            margin: 20px 0;
            font-size: 18px;
            font-weight: bold;
            color: #667eea;
        }
        
        .signature-container {
            margin-top: 50px;
        }
        
        .signature-area {
            display: flex;
            justify-content: space-between;
            margin-top: 40px;
        }
        
        .signature-box {
            width: 45%;
            position: relative;
        }
        
        .signature-label {
            margin-bottom: 8px;
            font-weight: 500;
        }
        
        .signature-field {
            height: 60px;
            border-bottom: 1px solid #667eea;
            margin-bottom: 20px;
            position: relative;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .signature-field:hover {
            background-color: rgba(102, 126, 234, 0.05);
        }
        
        .signature-image {
            max-height: 100%;
            max-width: 100%;
            object-fit: contain;
        }
        
        .signature-info {
            display: flex;
            justify-content: space-between;
        }
        
        .signature-date {
            width: 100%;
            text-align: center;
        }
        
        .date-input {
            display: inline-block;
            width: 40px;
            border-bottom: 1px solid #667eea;
            text-align: center;
            margin: 0 5px;
        }
        
        .note {
            margin-top: 30px;
            font-size: 16px;
            color: #333;
            padding: 20px;
            background-color: #f5f9ff;
            border-radius: 5px;
            border-left: 4px solid #667eea;
        }
        
        .note strong {
            font-size: 18px;
            color: #e74c3c;
        }
        
        .note ol {
            margin-top: 10px;
            padding-left: 20px;
            line-height: 1.8;
        }
        
        .controls {
            position: fixed;
            right: 30px;
            top: 50%;
            transform: translateY(-50%);
            display: flex;
            flex-direction: column;
            gap: 12px;
            z-index: 100;
        }
        
        button {
            padding: 10px 20px;
            cursor: pointer;
            border: none;
            border-radius: 25px;
            color: white;
            font-weight: bold;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
            justify-content: center;
        }
        
        button:hover {
            background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
            box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
            transform: translateY(-2px);
        }
        
        .purpose-box {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
            background-color: #f5f9ff;
        }
        
        .purpose-title {
            font-weight: bold;
            margin-bottom: 10px;
            color: #667eea;
        }
        
        #signature-upload {
            display: none;
        }
        
        /* 签名删除按钮样式 */
        .signature-delete-btn {
            display: none; /* 默认隐藏 */
            position: absolute;
            top: 5px;
            right: 5px;
            width: 24px;
            height: 24px;
            padding: 0;
            border-radius: 50%;
            background-color: rgba(255, 0, 0, 0.7);
            color: white;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: opacity 0.3s ease;
        }
        
        /* 鼠标悬停在签名区域时显示删除按钮 */
        .signature-field:hover .signature-delete-btn {
            display: flex;
        }
        
        /* 模态框样式 */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: all 0.3s ease;
        }
        
        .modal-overlay.active {
            opacity: 1;
            visibility: visible;
        }
        
        .modal {
            background-color: white;
            padding: 25px;
            border-radius: 8px;
            width: 90%;
            max-width: 400px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            transform: translateY(-20px);
            transition: all 0.3s ease;
        }
        
        .modal-overlay.active .modal {
            transform: translateY(0);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        
        .modal-title {
            margin: 0;
            font-size: 18px;
            color: #2c3e50;
            font-weight: bold;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 20px;
            cursor: pointer;
            color: #666;
            padding: 0;
            display: inline-block;
            box-shadow: none;
        }
        
        .modal-body {
            margin-bottom: 20px;
            font-size: 16px;
            line-height: 1.6;
        }
        
        .modal-footer {
            text-align: right;
        }
        
        .modal-btn {
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
        }
        
        @media print {
            .no-print {
                display: none;
            }
            body {
                background: none;
            }
            .container {
                padding: 0;
                width: auto;
                margin: 20px;
                box-shadow: none;
            }
            button {
                display: none;
            }
            .report-title {
                font-size: 24px;
            }
        }
    </style>
</head>
<body>
    <div class="controls no-print">
        <button onclick="addRow()"><i class="fa fa-plus"></i> 增加物品</button>
        <button onclick="removeRow()"><i class="fa fa-minus"></i> 删除物品</button>
        <button onclick="calculateTotal()"><i class="fa fa-calculator"></i> 计算总价</button>
        <button onclick="window.print()"><i class="fa fa-print"></i> 打印</button>
    </div>
    
    <!-- 文件上传控件 -->
    <input type="file" id="signature-upload" accept="image/*" class="no-print">
    
    <!-- 模态框 -->
    <div class="modal-overlay no-print" id="modal">
        <div class="modal">
            <div class="modal-header">
                <h3 class="modal-title" id="modal-title">提示</h3>
                <button class="modal-close" onclick="hideModal()">&times;</button>
            </div>
            <div class="modal-body" id="modal-message">
                这是一条提示信息
            </div>
            <div class="modal-footer">
                <button class="modal-btn" onclick="hideModal()">确定</button>
            </div>
        </div>
    </div>
    
    <div class="container">
        <div class="header">
            <div class="report-title" contenteditable="true">物品采购清单</div>
        </div>
        
        <div class="purchase-info">
            <div>采购部门：<span class="editable" id="department" contenteditable="true"></span></div>
            <div>采购人：<span class="editable" id="purchaser" contenteditable="true"></span></div>
            <div>采购日期：<span class="editable" id="purchase-date" contenteditable="true"></span></div>
        </div>
        
        <div class="purpose-box">
            <div class="purpose-title">采购用途：</div>
            <div class="editable" contenteditable="true" style="min-height: 80px; line-height: 1.6;">
                请说明本次采购物品的用途和必要性
            </div>
        </div>
        
        <table id="purchase-table">
            <thead>
                <tr>
                    <th width="10%">序号</th>
                    <th width="25%">物品名称</th>
                    <th width="10%">数量</th>
                    <th width="10%">单位</th>
                    <th width="15%">单价 (¥)</th>
                    <th width="15%">金额 (¥)</th>
                    <th width="15%">备注</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>1</td>
                    <td><div class="editable" contenteditable="true"></div></td>
                    <td><div class="editable number" contenteditable="true">1</div></td>
                    <td><div class="editable" contenteditable="true">个</div></td>
                    <td><div class="editable number" contenteditable="true">0.00</div></td>
                    <td><div class="amount">0.00</div></td>
                    <td><div class="editable" contenteditable="true"></div></td>
                </tr>
                <tr>
                    <td>2</td>
                    <td><div class="editable" contenteditable="true"></div></td>
                    <td><div class="editable number" contenteditable="true">1</div></td>
                    <td><div class="editable" contenteditable="true">个</div></td>
                    <td><div class="editable number" contenteditable="true">0.00</div></td>
                    <td><div class="amount">0.00</div></td>
                    <td><div class="editable" contenteditable="true"></div></td>
                </tr>
                <tr>
                    <td>3</td>
                    <td><div class="editable" contenteditable="true"></div></td>
                    <td><div class="editable number" contenteditable="true">1</div></td>
                    <td><div class="editable" contenteditable="true">个</div></td>
                    <td><div class="editable number" contenteditable="true">0.00</div></td>
                    <td><div class="amount">0.00</div></td>
                    <td><div class="editable" contenteditable="true"></div></td>
                </tr>
            </tbody>
        </table>
        
        <div class="summary">
            采购总金额：<span id="total-amount">¥0.00</span>
        </div>
        
        <div class="signature-container">
            <div class="signature-area">
                <div class="signature-box">
                    <div class="signature-label">采购人（签字）</div>
                    <div class="signature-field" data-role="purchaser"></div>
                    <div class="signature-info">
                        <div class="signature-date">
                            日期：
                            <span class="date-input editable" contenteditable="true"></span>年
                            <span class="date-input editable" contenteditable="true"></span>月
                            <span class="date-input editable" contenteditable="true"></span>日
                        </div>
                    </div>
                </div>
                
                <div class="signature-box">
                    <div class="signature-label">审批人（签字）</div>
                    <div class="signature-field" data-role="approver"></div>
                    <div class="signature-info">
                        <div class="signature-date">
                            日期：
                            <span class="date-input editable" contenteditable="true"></span>年
                            <span class="date-input editable" contenteditable="true"></span>月
                            <span class="date-input editable" contenteditable="true"></span>日
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="note">
            <strong>注意：</strong>
            <ol>
                <li>单价和金额需保留两位小数，金额计算应准确无误。</li>
                <li>采购用途需详细说明，包括物品使用场景和必要性，以便审批。</li>
                <li>所有签名必须为本人亲笔签名或有效的电子签名，代签无效。</li>
                <li>请如实、准确填写所有采购物品信息，确保规格、数量与实际相符。</li>
            </ol>
        </div>
    </div>

    <script>
        // 当前选中的签名区域
        let currentSignatureField = null;
        const modal = document.getElementById('modal');
        const modalTitle = document.getElementById('modal-title');
        const modalMessage = document.getElementById('modal-message');
        
        // 显示模态框
        function showModal(title, message) {
            modalTitle.textContent = title;
            modalMessage.textContent = message;
            modal.classList.add('active');
            // 阻止背景滚动
            document.body.style.overflow = 'hidden';
        }
        
        // 隐藏模态框
        function hideModal() {
            modal.classList.remove('active');
            // 恢复背景滚动
            document.body.style.overflow = '';
        }
        
        // 点击模态框外部关闭
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                hideModal();
            }
        });
        
        // 按ESC键关闭模态框
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.classList.contains('active')) {
                hideModal();
            }
        });
        
        // 增加行
        function addRow() {
            const table = document.querySelector('#purchase-table tbody');
            const rowCount = table.rows.length + 1;
            const newRow = table.insertRow();
            
            newRow.innerHTML = `
                <td>${rowCount}</td>
                <td><div class="editable" contenteditable="true"></div></td>
                <td><div class="editable number" contenteditable="true">1</div></td>
                <td><div class="editable" contenteditable="true">个</div></td>
                <td><div class="editable number" contenteditable="true">0.00</div></td>
                <td><div class="amount">0.00</div></td>
                <td><div class="editable" contenteditable="true"></div></td>
            `;
            
            // 为新添加的数字输入框添加事件监听
            attachNumberInputHandlers(newRow.querySelectorAll('.number'));
            
            showModal('操作成功', '已成功添加一行物品信息');
        }
        
        // 删除行
        function removeRow() {
            const table = document.querySelector('#purchase-table tbody');
            if (table.rows.length > 1) {
                table.deleteRow(table.rows.length - 1);
                // 重新编号
                const rows = table.querySelectorAll('tr');
                rows.forEach((row, index) => {
                    row.cells[0].textContent = index + 1;
                });
                // 重新计算总价
                calculateTotal();
                showModal('操作成功', '已成功删除一行物品信息');
            } else {
                showModal('操作提示', '至少保留一项物品，无法继续删除！');
            }
        }
        
        // 计算金额
        function calculateAmounts() {
            const rows = document.querySelectorAll('#purchase-table tbody tr');
            let total = 0;
            let hasInvalidData = false;
            
            rows.forEach(row => {
                const quantityEl = row.querySelector('td:nth-child(3) .editable');
                const priceEl = row.querySelector('td:nth-child(5) .editable');
                const amountEl = row.querySelector('td:nth-child(6) .amount');
                
                const quantity = parseFloat(quantityEl.textContent) || 0;
                const price = parseFloat(priceEl.textContent) || 0;
                
                // 检查是否有无效数据
                if (isNaN(quantity) || isNaN(price) || quantity < 0 || price < 0) {
                    hasInvalidData = true;
                }
                
                const amount = quantity * price;
                
                // 保留两位小数
                amountEl.textContent = amount.toFixed(2);
                total += amount;
            });
            
            // 更新总价
            document.getElementById('total-amount').textContent = `¥${total.toFixed(2)}`;
            
            // 如果有无效数据，显示提示
            if (hasInvalidData) {
                showModal('数据提示', '请注意：部分数据无效（非数字或负数），已按0处理');
            }
            
            return hasInvalidData;
        }
        
        // 计算总价（对外公开的函数）
        function calculateTotal() {
            const hasInvalid = calculateAmounts();
            if (!hasInvalid) {
                showModal('计算完成', '所有金额已重新计算');
            }
        }
        
        // 处理数字输入
        function handleNumberInput(e) {
            const cell = e.target;
            // 只允许数字和小数点
            let value = cell.textContent.trim();
            value = value.replace(/[^0-9.]/g, '');
            
            // 确保只有一个小数点
            if ((value.match(/\./g) || []).length > 1) {
                value = value.slice(0, value.lastIndexOf('.'));
            }
            
            // 限制小数点后两位
            if (value.includes('.')) {
                const parts = value.split('.');
                if (parts[1].length > 2) {
                    value = parts[0] + '.' + parts[1].substring(0, 2);
                }
            }
            
            cell.textContent = value;
            
            // 移动光标到末尾
            const range = document.createRange();
            const selection = window.getSelection();
            range.selectNodeContents(cell);
            range.collapse(false);
            selection.removeAllRanges();
            selection.addRange(range);
            
            // 实时计算金额
            calculateAmounts();
        }
        
        // 为数字输入框添加事件监听
        function attachNumberInputHandlers(elements) {
            elements.forEach(el => {
                el.addEventListener('input', handleNumberInput);
            });
        }
        
        // 处理签名上传
        function handleSignatureUpload(event) {
            if (!currentSignatureField) return;
            
            const file = event.target.files[0];
            if (!file) return;
            
            // 检查文件类型是否为图片
            if (!file.type.startsWith('image/')) {
                showModal('文件类型错误', '请上传图片文件（支持JPG、PNG等格式）！');
                return;
            }
            
            // 检查文件大小（限制10MB）
            if (file.size > 10 * 1024 * 1024) {
                showModal('文件过大', '图片文件大小不能超过10MB，请选择较小的图片！');
                return;
            }
            
            const reader = new FileReader();
            reader.onload = function(e) {
                // 清除现有内容
                currentSignatureField.innerHTML = '';
                
                // 创建图片元素
                const img = document.createElement('img');
                img.src = e.target.result;
                img.className = 'signature-image';
                img.alt = currentSignatureField.dataset.role === 'purchaser' ? '采购人签名' : '审批人签名';
                
                // 添加删除按钮，使用专门的类名
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'signature-delete-btn no-print';
                deleteBtn.innerHTML = '<i class="fa fa-times"></i>';
                
                deleteBtn.onclick = function(e) {
                    e.stopPropagation();
                    resetSignatureField(currentSignatureField);
                    showModal('操作成功', '已移除签名图片');
                };
                
                // 添加到签名区域
                currentSignatureField.appendChild(img);
                currentSignatureField.appendChild(deleteBtn);
                currentSignatureField.classList.add('has-signature');
                
                showModal('上传成功', '签名图片已成功上传');
            };
            
            reader.readAsDataURL(file);
            
            // 重置文件输入，以便可以重复选择同一个文件
            event.target.value = '';
        }
        
        // 重置签名区域
        function resetSignatureField(field) {
            field.innerHTML = '';
            field.classList.remove('has-signature');
        }
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 设置默认日期为今天
            const today = new Date();
            const formattedDate = `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`;
            document.getElementById('purchase-date').textContent = formattedDate;
            
            // 设置默认签名日期
            const year = today.getFullYear();
            const month = today.getMonth() + 1;
            const day = today.getDate();
            
            const dateInputs = document.querySelectorAll('.date-input');
            dateInputs[0].textContent = year;
            dateInputs[1].textContent = month;
            dateInputs[2].textContent = day;
            dateInputs[3].textContent = year;
            dateInputs[4].textContent = month;
            dateInputs[5].textContent = day;
            
            // 为数字输入框添加事件监听
            const numberInputs = document.querySelectorAll('.number');
            attachNumberInputHandlers(numberInputs);
            
            // 初始化计算
            calculateAmounts();
            
            // 签名区域点击事件
            const signatureFields = document.querySelectorAll('.signature-field');
            const fileInput = document.getElementById('signature-upload');
            
            signatureFields.forEach(field => {
                field.addEventListener('click', function() {
                    currentSignatureField = this;
                    fileInput.click();
                });
            });
            
            // 文件上传处理
            fileInput.addEventListener('change', handleSignatureUpload);
        });
    </script>
</body>
</html>